package com.cn.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.auth.model.vo.UserDetailsVO;
import com.cn.auth.utils.AuthTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author zhoujunming
 * @Description 将登录用户的JWT转化成用户信息的全局过滤器
 * @date 2022/6/8 16:49
 * @email zhoujunming@bluemoon.com.cn
 */
@Component
@Slf4j
public class AuthGlobalFilter  implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        // 1.鉴权放行  pathMatcher.match("/oauth/**",requestUrl)或者 pathMatcher.match("/login", requestUrl)路径是否匹配
        if (pathMatcher.match("/oauth/**", requestUrl) || pathMatcher.match("/login", requestUrl)) {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token.startsWith("Bearer ")){
            token = token.replace("Bearer ","");
        }
        if (null == token) {
            return noTokenMono(exchange);
        }
        try {
            //调用feign接口校验token是否生效
            AuthTokenUtils.validUserInfo(token);
        } catch (Exception e) {
            log.error("鉴权验证不通过，token= {}", token);
            return invalidTokenMono(exchange);
        }

        UserDetailsVO userDetailsVO = AuthTokenUtils.getUserInfo();
        ServerHttpRequest request = exchange.getRequest().mutate().header("user", JSON.toJSONString(userDetailsVO)).build();
        exchange = exchange.mutate().request(request).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 没有token
     * @param exchange
     * @return
     */
    private Mono<Void> noTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED);
        json.put("data", "没有token");
        return jsonToMono(json, exchange);
    }

    /**
     * 将json字符串转换为Mono的格式,并添加到相应中去
     * @param json
     * @param exchange
     * @return
     */
    private Mono<Void> jsonToMono(JSONObject json, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = json.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        response.setStatusCode(org.springframework.http.HttpStatus.valueOf(HttpStatus.UNAUTHORIZED.name()));
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(dataBuffer));
    }


    private Mono<Void> invalidTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED.value());
        json.put("data", "无效的token");
        return jsonToMono(json, exchange);
    }
    private Mono<Void> notLogin(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.NON_AUTHORITATIVE_INFORMATION);
        json.put("data", "请重新登录");
        return jsonToMono(json, exchange);
    }
}
